package com.android.widget.demo;

import android.app.Activity;
import android.app.DatePickerDialog;
import android.app.admin.DevicePolicyManager;
import android.content.ComponentName;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.ImageView;
import android.widget.TextView;

import com.android.widget.spinneAndTableLayout.SpinnerActivity;
import com.android.widget.datepicker.YearMonthPickerDialog;
import com.android.widget.gesture.GestureTest;
import com.android.widget.gridview.GridViewSimple;
import com.android.widget.imgtxtimg.*;
import com.android.widget.radio.RadioGroupActivity;
import com.android.widget.horizontallistview.HorizontalListViewDemo;
import com.android.widget.horizontalscrollview.HorizontalScrollViewDemo;
import com.android.widget.horizontalscrollview2.HorizontalScrollViewDemo2;
import com.android.widget.swipelistview.SwipeListViewActivity;
import com.linc.Properties.PropertiesActivity;
import com.linc.android.app.AdminReceiver;
import com.linc.android.app.DateUtils;
import com.linc.android.app.exit.*;
import com.linc.base64.Base64Activity;
import com.linc.camera.CameraActivity;
import com.linc.camera.IntentCameraActivity;
import com.linc.countdown.CountDownActivity;
import com.linc.facerecongnize.FaceDetectActivity;
import com.linc.intercept.SmsInterceptActivity;
import com.linc.skill.screenswitch.ScreenSwichActivity;
import com.linc.skill.thread.ThreadActivity;

import java.io.FileNotFoundException;
import java.util.Calendar;
import java.util.Date;

public class MainActivity extends BaseActivity {
    private final static String TAG = "MainActivity";
    private DevicePolicyManager policyManager;
    private ComponentName componentName;
    private static final int LOCK_SCREEN_REQUEST_CODE = 9999;
    private static final int OPEN_PHOTO_FOLDER_REQUEST_CODE = 9998;

    private ImageView mImgPhoto;
    private TextView mTextView;
    @Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		initView();
	}

	private void initView() {
        mTextView = (TextView)findViewById(R.id.txt_show);
        mImgPhoto = (ImageView)findViewById(R.id.img_photo);
		Button btnGridViewSimple = (Button)findViewById(R.id.btn_gridview_simple);
		btnGridViewSimple.setOnClickListener(buttonListener);
		Button btnGestureTest = (Button)findViewById(R.id.btn_gesture_test);
		btnGestureTest.setOnClickListener(buttonListener);	
		Button btnImgTxtImg = (Button) findViewById(R.id.btn_imgtxtimg);
		btnImgTxtImg.setOnClickListener(buttonListener);	
        Button btnRadio = (Button)findViewById(R.id.btn_radio);
        btnRadio.setOnClickListener(buttonListener);
        findViewById(R.id.btn_activity_manager).setOnClickListener(buttonListener);
        findViewById(R.id.btn_horizontal_listview).setOnClickListener(buttonListener);
        findViewById(R.id.btn_horizontal_scroll_view).setOnClickListener(buttonListener);
        findViewById(R.id.btn_horizontal_scroll_view2).setOnClickListener(buttonListener);
        findViewById(R.id.btn_year_month_picker).setOnClickListener(buttonListener);
        findViewById(R.id.btn_screen_switch).setOnClickListener(buttonListener);
        findViewById(R.id.btn_lock_screen).setOnClickListener(buttonListener);
	}	
	
	private OnClickListener buttonListener = new OnClickListener() {
		@Override
		public void onClick(View v) {
			switch(v.getId()) {
			case R.id.btn_gridview_simple:
				startActivity(new Intent(MainActivity.this,GridViewSimple.class));
				break;
			case R.id.btn_gesture_test:
				startActivity(new Intent(MainActivity.this,GestureTest.class));
				break;
			case R.id.btn_imgtxtimg:
				startActivity(new Intent(MainActivity.this,ImgTxtImgListViewActivity.class));
				break;
           case R.id.btn_radio:
                startActivity(new Intent(MainActivity.this,RadioGroupActivity.class));
                break;
           case R.id.btn_activity_manager:
                startActivity(new Intent(MainActivity.this,DemoA.class));
                break;
			case R.id.btn_horizontal_listview:
				startActivity(new Intent(MainActivity.this,HorizontalListViewDemo.class));	
				break;
            case R.id.btn_horizontal_scroll_view:
                startActivity(new Intent(MainActivity.this,HorizontalScrollViewDemo.class));  				
				break;
            case R.id.btn_horizontal_scroll_view2:
                startActivity(new Intent(MainActivity.this,HorizontalScrollViewDemo2.class));                
                break;
            case R.id.btn_year_month_picker:
                showYearMonthPicker();
                break;
            case R.id.btn_screen_switch:
                Log.d("linc", "press screen switch");
                startActivity(new Intent(MainActivity.this, ScreenSwichActivity.class));
                break;
            case R.id.btn_lock_screen:
                lockScreen();
                break;
			}
		}
	};

    public void onCanvasDemoClicked(View view) {
        startActivity(new Intent(MainActivity.this, com.linc.canvas.demo.MainActivity.class));
    }

    public void onOpenPhotoFolderClicked(View view) {
        Intent intent = new Intent();
        intent.setType("image/*");
        intent.setAction(Intent.ACTION_GET_CONTENT);
        startActivityForResult(intent, OPEN_PHOTO_FOLDER_REQUEST_CODE);
    }

    public void onFaceRecClicked(View view) {
        startActivity(new Intent(MainActivity.this, FaceDetectActivity.class));
    }

    public void onCameraDemoClicked(View view) {
        startActivity(new Intent(MainActivity.this, IntentCameraActivity.class));
    }

    public void onCameraDemo2Clicked(View view) {
        startActivity(new Intent(MainActivity.this, CameraActivity.class));
    }

    public void onSpinnerClicked(View view) {
        startActivity(new Intent(MainActivity.this, SpinnerActivity.class));
    }

    public void onSwipeListClicked(View view) {
        startActivity(new Intent(MainActivity.this, SwipeListViewActivity.class));
    }

    public void onBase64Clicked(View view) {
        startActivity(new Intent(MainActivity.this, Base64Activity.class));
    }

    public void onCountdownClicked(View view) {
        startActivity(new Intent(MainActivity.this, CountDownActivity.class));
    }

    public void onInterceptClicked(View view) {
        startActivity(new Intent(MainActivity.this, SmsInterceptActivity.class));
    }

    public void onThreadClicked(View view) {
        startActivity(new Intent(this, ThreadActivity.class));
    }

    public void onPropertiesClicked(View view) {
        startActivity(new Intent(this, PropertiesActivity.class));
    }

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.main, menu);
		return true;
	}

    public void showYearMonthPicker() {
        final Calendar localCalendar = Calendar.getInstance();
        Date date = new Date();
        localCalendar.setTime(date);
        new YearMonthPickerDialog(this,new DatePickerDialog.OnDateSetListener() {
            @Override
            public void onDateSet(DatePicker view, int year,int monthOfYear, int dayOfMonth) {
                monthOfYear++;
                String showDate = year+"-"+monthOfYear;
                String valueDate = year+""+monthOfYear;
                Date date;
                date = DateUtils.getDateByFormat(showDate, "yyyy-MM");
                showDate = DateUtils.getStringByFormat(date,"yyyy-MM");
                mTextView.setText(showDate);
                date = DateUtils.getDateByFormat(valueDate, "yyyyMM");
                valueDate = DateUtils.getStringByFormat(date,"yyyyMM");
                mTextView.append("\n"+valueDate);

            }
        }, localCalendar.get(Calendar.YEAR), localCalendar.get(Calendar.MONTH),
                localCalendar.get(Calendar.DATE)).show();
    }

    private void lockScreen() {
        //获取设备管理服务
        policyManager = (DevicePolicyManager) getSystemService(Context.DEVICE_POLICY_SERVICE);
        componentName = new ComponentName(this, AdminReceiver.class);
                /*
                * 假如先判断是否有权限，如果没有则调用activeManage()，然后立即锁屏，再finish()。
                * 这样做是有问题的，因为activeManage()可能还在等待另一个Activity的结果，那么此时依然没有权限却
                * 执行了lockNow()，这样就出错了。
                * 处理方法有2个：
                * 1、是重写OnActivityResult()函数，在里面判断是否获取权限成功，是则锁屏并finish()
                * 否则继续调用activeManage()获取权限（这样激活后立即锁屏，效果很好）
                * 2、不重写OnActivityResult()函数，第一次获取权限后不锁屏而立即finish()，这样从理论上说也可能
                * 失败，可能权限还没获取好就finish了（这样激活后就回到桌面，还得再按一次锁屏才能锁）
                * 综上推荐第一种方法。*/

        //判断是否有锁屏权限，若有则立即锁屏并结束自己，若没有则获取权限
        if (policyManager.isAdminActive(componentName))
        {
            policyManager.lockNow();
            finish();
        }
        else
        {
            activeManage();
        }
    }
    private void activeManage() {
        // 启动设备管理(隐式Intent) - 在AndroidManifest.xml中设定相应过滤器
        Intent intent = new Intent(DevicePolicyManager.ACTION_ADD_DEVICE_ADMIN);
        //权限列表
        intent.putExtra(DevicePolicyManager.EXTRA_DEVICE_ADMIN, componentName);
        //描述(additional explanation)
        intent.putExtra(DevicePolicyManager.EXTRA_ADD_EXPLANATION, "Active LockScreen Manager!");
        startActivityForResult(intent, LOCK_SCREEN_REQUEST_CODE);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data)
    {
        //获取权限成功，立即锁屏并finish自己，否则继续获取权限
        if (requestCode == LOCK_SCREEN_REQUEST_CODE) {
            if(resultCode == Activity.RESULT_OK) {
                policyManager.lockNow();
                finish();
            } else {
                activeManage();
            }
        } else if(requestCode == OPEN_PHOTO_FOLDER_REQUEST_CODE) {
            if(RESULT_OK == resultCode) {
                //show photo you selected
                Uri uri = data.getData();
                ContentResolver resolver = this.getContentResolver();
                try {
                    Bitmap bitmap = BitmapFactory.decodeStream(resolver.openInputStream(uri));
                    mImgPhoto.setVisibility(View.VISIBLE);
                    mImgPhoto.setImageBitmap(bitmap);
                } catch (FileNotFoundException ex) {
                    Log.e(TAG,"failed."+ex.getMessage());
                }

            }
        }

        super.onActivityResult(requestCode, resultCode, data);
    }

}
